package curso.ejercicios;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class MultiToquePantalla extends Activity implements OnTouchListener {

	private StringBuilder mensajes = new StringBuilder();
	private TextView visor;
	private int MAX = 10;

	private float[] x = new float[MAX];
	private float[] y = new float[MAX];
	private boolean[] toque = new boolean[MAX];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		visor = new TextView(this);
		visor.setText("Toca la pantalla con varios dedos");
		visor.setOnTouchListener(this);
		setContentView(visor);
		updateScreen();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		int action = event.getAction() & MotionEvent.ACTION_MASK;
		int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
		int pointerId = event.getPointerId(pointerIndex);

		switch (action) {
		case MotionEvent.ACTION_DOWN:
		case MotionEvent.ACTION_POINTER_DOWN:
			toque[pointerId] = true;
			x[pointerId] = (int) event.getX(pointerIndex);
			y[pointerId] = (int) event.getY(pointerIndex);
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
		case MotionEvent.ACTION_CANCEL:
			toque[pointerId] = false;
			x[pointerId] = (int) event.getX(pointerIndex);
			y[pointerId] = (int) event.getY(pointerIndex);
			break;
		case MotionEvent.ACTION_MOVE:
			int fingerCount = event.getPointerCount();
			for (int i = 0; i < fingerCount; i++) {
				pointerIndex = i;
				pointerId = event.getPointerId(pointerIndex);
				x[pointerId] = (int) event.getX(pointerIndex);
				y[pointerId] = (int) event.getY(pointerIndex);
			}
			break;
		}

		updateScreen();

		return true;
	}

	private void updateScreen() {
		mensajes.setLength(0);
		for (int i = 0; i < MAX; i++) {
			mensajes.append("Dedo " + (i + 1) + ": ");
			mensajes.append(toque[i] + ", ");
			mensajes.append(x[i] + ", ");
			mensajes.append(y[i] + "\n");
		}
		visor.setText(mensajes.toString());
	}

}
